import type { Canceler } from 'axios';

interface RequestItem {
    id: string;
    cancel: Canceler | (() => void);
    timestamp: number;
}

class RequestManager {
    private static instance: RequestManager;
    private requests: Map<string, RequestItem>;

    private constructor() {
        this.requests = new Map();
    }

    public static getInstance(): RequestManager {
        if (!RequestManager.instance) {
            RequestManager.instance = new RequestManager();
        }
        return RequestManager.instance;
    }

    /**
     * 添加请求到管理器
     * @param id 请求唯一标识
     * @param cancel 取消函数
     */
    public addRequest(id: string, cancel: Canceler | (() => void)): void {
        this.requests.set(id, {
            id,
            cancel,
            timestamp: Date.now(),
        });
    }

    /**
     * 从管理器中移除请求
     * @param id 请求唯一标识
     */
    public removeRequest(id: string): void {
        this.requests.delete(id);
    }

    /**
     * 取消指定请求
     * @param id 请求唯一标识
     */
    public cancelRequest(id: string): void {
        const request = this.requests.get(id);
        if (request) {
            request.cancel();
            this.removeRequest(id);
        }
    }

    /**
     * 取消所有请求
     */
    public cancelAll(): void {
        this.requests.forEach((request) => {
            request.cancel();
        });
        this.requests.clear();
    }

    /**
     * 取消指定组的所有请求
     * @param groupId 组标识（例如组件名称）
     */
    public cancelGroup(groupId: string): void {
        this.requests.forEach((request, id) => {
            if (id.startsWith(groupId)) {
                request.cancel();
                this.removeRequest(id);
            }
        });
    }

    /**
     * 获取当前请求数量
     */
    public getRequestCount(): number {
        return this.requests.size;
    }

    /**
     * 清理过期的请求
     * @param maxAge 最大存活时间（毫秒）
     */
    public clearStaleRequests(maxAge: number = 30000): void {
        const now = Date.now();
        this.requests.forEach((request, id) => {
            if (now - request.timestamp > maxAge) {
                this.cancelRequest(id);
            }
        });
    }
}

export const requestManager = RequestManager.getInstance();
